﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace BSPortal.Usercontrol
{
    public partial class DiscountProduct : System.Web.UI.UserControl
    {
        public int PageSize;
        private int RowCount;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadData(0);
            CreatePagingControl();
        }

        protected void LoadData(int skip)
        {
            var listProduct = Common.GetClientService().GetListDiscountProduct(Common.GetLine()).FindAll(row => (bool)row.IsPublished == true).Take(20);
            var data = listProduct.Skip(skip).Take(PageSize);

            productRepeater.DataSource = data;
            productRepeater.DataBind();

            RowCount = listProduct.Count();
            if (RowCount > PageSize)
                pagingDiv.Visible = true;
            else
                pagingDiv.Visible = false;
        }

        private void CreatePagingControl()
        {
            int pages = (((RowCount%PageSize) > 0) ? (RowCount/PageSize) + 1 : (RowCount/PageSize));
            if(pages<2)
            {
                plcPaging.Visible = false;
                return;
            }

            for (int i = 0; i < pages; i++)
            {
                LinkButton lnk = new LinkButton();
                lnk.Click += new EventHandler(LblClick);
                lnk.ID = "lnkPage" + (i + 1).ToString();
                lnk.Text = (i + 1).ToString();
                plcPaging.Controls.Add(lnk);
                Label spacer = new Label();
                spacer.Text = "&nbsp;";
                plcPaging.Controls.Add(spacer);
            }
        }

        void LblClick(object sender, EventArgs e)
        {
            LinkButton lnk = sender as LinkButton;
            int currentPage = int.Parse(lnk.Text);
            int skip = (currentPage - 1) * PageSize;
            LoadData(skip);
        }

        public static string GetDiscountPrice(int price, float discount)
        {
            float result = price*(1 - discount);
            result = (result/100)*100;
            return result.ToString("#,###");
        }
    }
}